package com.peter.core;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Created by zmy on 2018/4/4.
 */
public final class JdbcUtils {
    private static String USERNAME;
    private static String PASSWORD;
    private static String URL;
    private static String DRIVER;

    static {
        //加载数据库配置信息
        loadConfig();
    }

    /**
     * 加载数据库配置信息
     */
    private static void loadConfig() {
        try {
            InputStream inputStream = JdbcUtils.class.getResourceAsStream("/jdbc.properties");
            Properties prop = new Properties();
            prop.load(inputStream);
            USERNAME = prop.getProperty("jdbc.username");
            PASSWORD = prop.getProperty("jdbc.password");
            DRIVER = prop.getProperty("jdbc.driver");
            URL = prop.getProperty("jdbc.url");
        } catch (IOException e) {
            throw new RuntimeException("读取数据库配置文件失败!", e);
        }
    }

    /**
     * 获取链接
     *
     * @return
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            Class.forName(DRIVER);
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("注册驱动失败", e);
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接失败", e);
        }
        return connection;
    }

    /**
     * 释放资源
     */
    public static void release(Connection connection, PreparedStatement pstmt, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException("关闭结果集失败", e);
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                throw new RuntimeException("close PreparedStatement fail", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException("释放连接失败", e);
            }
        }
    }

    public static void main(String[] args) {
        Connection connection = JdbcUtils.getConnection();
    }
}
